// define('main',function(){
//   alert(1);
//   return 123;
// });
require(['modules/fetch'],function(fetch){


    //loadSidebarData(PageData.storyInfo.node_id);

    var loadStoryChapterListFn = function (storyId){
        fetch('listChaptersByStoryId', { ps: 20, pn: 0, story_id: storyId},
            function (result) {
                if(0 == result.errno ){
                    vmData.sidebarDataList = result.data.list;
                }
            },
            function(data) {
                console.log("ajax faild");
            }
        );
    }

    var newNode = {
            content:'',
        };
    var vmData = {
        storyInfo: _.clone(PageData.storyInfo),
        nodeInfo: _.clone(PageData.nodeInfo),
        story_id: 0,
        node_id: 0,
        title:'',
        content:'',
        content_preview:'',
        nodes:[
            _.clone(newNode),
            _.clone(newNode)
        ],
        sidebarDataList:[],
    };
    var vm = new Vue({
        el: "#vue-app",
        data: vmData,
        methods:{
            submitEditChapterForm: function(){
                console.log(arguments)
                console.log(vmData);

                var formData = {
                    title: vmData.title,
                    content: vmData.content,
                    story_id: PageData.storyInfo.story_id,
                    node_id: PageData.nodeInfo.node_id,
                }
   
                formData['nodes'] = _.map(vmData.nodes, function(item){ 
                    return { 
                        content: item.content,
                        node_id: item.node_id,
                    } 
                });

                fetch('postChapter',formData ,
                    function (result) {
                        if(0 == result.errno){
                            alert("发布成功!");
                            location.href="/chapter/readChapter?chapter_id=" + result.data.chapter_id;
                        } else {
                            alert("发布失败!");
                        }
                    },
                    function(data) {
                        console.log("ajax faild");
                    }
                );
                return false;
            },
            editChapterContentChange: function(){
                vmData.content_preview = markdown.toHTML(vmData.content);
            },
            addNode: function(){
                vmData.nodes.push(_.clone(newNode));
                return false;
            },
            remNode: function(index){
                vmData.nodes.splice(index, 1);
            },

            sidebarItemClick: function(item, index) {
                //getChapterInfo(parseInt(item.chapter_id));
                location.href="/chapter/readChapter?chapter_id=" + parseInt(item.chapter_id); 
            }
        }
    });
    loadStoryChapterListFn(PageData.storyInfo.story_id);
});